package 力扣.回溯;


import java.util.ArrayList;
import java.util.List;

public class 二叉树的所有路径257 {
    private class TreeNode{
        private int val;
        private TreeNode left;
        private TreeNode right;
        TreeNode(int val){
            this.val = val;
        }
    }
    public List<String> binaryTreePaths(TreeNode root) {
          if (root == null){
              return new ArrayList<>();
          }
          List<String> ans = new ArrayList<>();
          String str = "";
          preDfs(root,ans,"");
          return ans;
    }

    private void preDfs(TreeNode root, List<String> ans, String string) {
        if (root != null){
            StringBuilder str = new StringBuilder(string);//将其设为局部变量就可以不用回溯了
            str.append(root.val);
            if (root.left == null && root.right == null){
                ans.add(str.toString());
            }else {
                str.append("->");//不是叶子的话加上
                if (root.left != null){
                    preDfs(root.left, ans, str.toString());
                }
                if (root.right != null){
                    preDfs(root.right, ans, str.toString());
                }
            }
        }
    }
}
